package com.yzh.wanandroid.component.fragment

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.yzh.wanandroid.R
import com.yzh.wanandroid.adapter.SquareAdapter
import com.yzh.wanandroid.base.MvvmFragment
import com.yzh.wanandroid.databinding.FragmentSquarePagerBinding
import com.yzh.wanandroid.vm.SquarePagerFragmentVm
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class SquarePagerFragment : MvvmFragment<FragmentSquarePagerBinding, SquarePagerFragmentVm>() {

    private val TAG = "SquarePagerFragment"

    private val mAdapter by lazy { SquareAdapter() }

    override fun getLayoutId() = R.layout.fragment_square_pager

    override fun initViewModel(): SquarePagerFragmentVm = createViewModel()

    companion object {
        fun getInstance() = SquarePagerFragment()
    }

    override fun initView(view: View) {
        initRecyclerView()
        initSwipeRefresh()
    }

    override fun initData() {
        initBinding()
    }

    override fun onLazyLoad() {
        super.onLazyLoad()
        loadSquareData()
    }

    private fun initBinding() {
        mBinding.run {
            netWorkData = mViewModel.netWorkData
            squareAdapter = mAdapter
            refreshData = mAdapter.refreshData
            squareFragment = this@SquarePagerFragment
        }
    }

    private fun initRecyclerView() {
        mBinding.run {
            var linearLayoutManager = LinearLayoutManager(requireActivity())
            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
            squareList.layoutManager = linearLayoutManager
        }
    }

    /**
     * 初始化 SwipeRefreshLayout
     */
    private fun initSwipeRefresh() {
        mBinding.run {
            squareSwipeRefresh.setColorSchemeResources(R.color.color_main)
            squareSwipeRefresh.setOnRefreshListener { initData() }
        }
    }

    /**
     *  加载文章
     */
    private fun loadSquareData() {
        lifecycleScope.launch {
            try {
                mViewModel.getData().collectLatest {
                    mAdapter.submitData(it)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 点击重新加载按钮
     */
    fun onReloadClick() {

    }
}